import { Loader } from "@googlemaps/js-api-loader"; //引入
import { flatMapDepth } from "lodash-es";
const loader = new Loader({
    apiKey: "AIzaSyAz3DEfRO5DT3qfSFbmccnAmRP3lUR5DV0",//之前的key
    version: "weekly",//版本
    libraries: ["places"],
    language: "en-us"
});
export function useGoogleMap(elementId, proxy) {
    var map, mapObj, geocoder
    var lastMarker

    async function initMap(lng = '', lat = '', address = '') {
        return new Promise(resolve => {
            if (map) {
                if (lng != '') {
                    lng = parseFloat(lng)
                    lat = parseFloat(lat)
                    addMarker({
                        lng: lng, 
                        lat: lat, 
                        address: address
                    })
                }
                resolve()
            }
            const mapOptions = {
                center: {
                    lat: 40.7127753,
                    lng: -74.0059728
                  },
                zoom: 12,
                disableDefaultUI: true,
                styles: [ 
                    { 
                    "featureType": "poi", 
                    "stylers": [ 
                    { "visibility": "off" } 
                    ] 
                } ,
                { 
                    "featureType": "transit", 
                    "stylers": [ 
                    { "visibility": "off" } 
                    ] 
                } 
                ]
            };

            loader
                .load()
                .then((google) => {
                    map = new google.maps.Map(
                        document.getElementById(elementId),
                        mapOptions
                    );
                    mapObj = google
                    geocoder = new google.maps.Geocoder();
                    if (lng != '') {
                        lng = parseFloat(lng)
                        lat = parseFloat(lat)
                        addMarker({
                            lng: lng, 
                            lat: lat, 
                            address: address
                        })
                    }
                    console.log('goo==', google)
                    resolve(google)
                })
                .catch((e) => {
                    // do something
                    console.log(e);
                });
        })
    }
    function mapSearch(keyword, cb) {
        geocoder.geocode({ 'address': keyword }, function (results, status) {
            if (status == 'OK') {
                let arr = []
                results.forEach(element => {
                    console.log('element===', element)
                    let loc = JSON.parse(JSON.stringify(element.geometry.location))
                    let location = [loc.lng, loc.lat]
                    arr.push({
                        value: element.formatted_address,
                        link: {
                            address: element.formatted_address,
                            location: location
                        },
                    })
                });
                cb(arr)
            } else {
                console.log('Geocode was not successful for the following reason: ' + status);
            }
        });
    }

    function addMarker(item) {
        if (lastMarker) {
            lastMarker = null
        }
        let lng = parseFloat(item.lng)
        let lat = parseFloat(item.lat)
        let center = { lat: lat, lng: lng };
        setMapCenter(center)
        lastMarker = new google.maps.Marker({
            position: center,
            map,
        });
    }


    function createMarkers(item) {
        if (item.lng == '' || item.lat == '') {
            return
        }
        var marker
        if (item.alarm_status > 0) {
            marker = new mapObj.maps.Marker({
                position: new mapObj.maps.LatLng(parseFloat(item.lat), parseFloat(item.lng)),   // 经纬度对象，也可以是经纬度构成的一维数组[116.39, 39.9]
                title: item.address,
                icon: getIconUrl(item.alarm_status),
                animation: mapObj.maps.Animation.BOUNCE,
                offset: [-16, -32]
            });
        } else {
            marker = new mapObj.maps.Marker({
                position: new mapObj.maps.LatLng(parseFloat(item.lat), parseFloat(item.lng)),   // 经纬度对象，也可以是经纬度构成的一维数组[116.39, 39.9]
                title: item.address,
                icon: getIconUrl(item.alarm_status),
                offset: [-16, -32]
            });
        }
        mapObj.maps.event.addListener(marker, "click", () => {
            proxy.handleMarkerClick(item)
        })

        if (!window.markerMap) {
            window.globalMarkers = []
            window.markerMap = []
            window.markerInfo = []
        }
        window.markerMap[item.sn] = marker
        window.markerInfo[item.sn] = item
        window.globalMarkers.push(marker)
    }

    function addMarkersToMap() {
        if (!window.globalMarkers) {
            return
        }
        // map.add(window.globalMarkers)
        window.globalMarkers.forEach(ele => {
            ele.setMap(map);
        })
        map.setCenter(window.globalMarkers[0].getPosition())
    }

    function setMapCenter(item, zoom = 0) {
        if (item.lng == '' || item.lat == '') {
            return
        }
        if (zoom > 0) {
            map.setZoom(zoom);
        }
        map.setCenter(new mapObj.maps.LatLng(parseFloat(item.lat), parseFloat(item.lng)))
    }

    function changeMarkerStatus(item) {
        console.log('item===', item)
        if (window.markerMap[item.sn]) {
            let status = item.alarm_status || -1
            if (status < 0) {
                status = item.info.alarm_status
            }
            window.markerMap[item.sn].setIcon(getIconUrl(status))
            if (status > 0) {
                window.markerMap[item.sn].setAnimation(mapObj.maps.Animation.BOUNCE);
            } else {
                window.markerMap[item.sn].setAnimation(null);
            }
            // map.setCenter(window.markerMap[item.sn].getPosition())
        }
    }

    function getIconUrl(alarmStatus = 0) {
        let iconUrl = 'https://qiniu.change90.com/icon/normal.png'
        if (alarmStatus) {
            switch (alarmStatus) {
                case 0:
                    iconUrl = 'https://qiniu.change90.com/icon/normal.png'
                    break
                case 1:
                    iconUrl = 'https://qiniu.change90.com/icon/warning.png'
                    break
                case 2:
                    iconUrl = 'https://qiniu.change90.com/icon/fault.png'
                    break
            }
        }
        return iconUrl
    }

    function alertInfoWindow(item, dom, from = 'marker') {
        console.log('from-==', from, item)
        if (!window.markerMap[item.sn]) {
            return
        }
        if (window.infoWindow) {
            window.infoWindow.close()
        }
        
        window.infoWindow = new mapObj.maps.InfoWindow({
            content: dom,
            // pixelOffset: new mapObj.maps.Point(-150, -230)
        });
        
        window.infoWindow.open(map, window.markerMap[item.sn]);
        // if (item.alarm_status == 1) {
        //     setTimeout(() => {
        //         document.getElementsByClassName('gm-ui-hover-effect')[0].style.color = '#fff !important'
        //         document.getElementsByClassName('gm-style-iw-d')[0].style.overflow = 'auto'
        //         document.getElementsByClassName('gm-style-iw')[0].style.background = 'rgba(0,0,0,0.6)'
        //     }, 100);
           
        // }
        // 解决2.0版本无法滚动问题
        // infoWindow.on('mouseover', () => map.setStatus({ scrollWheel: false }))
        // infoWindow.on('mouseout', () => {
        //     map.setStatus({ scrollWheel: true })
        // })

        proxy.showDiv = true
    }



    function closeInfoWindow() {
        proxy.showDiv = false
        window.infoWindow.close();
    }
    return {
        initMap,
        mapSearch,
        addMarker,
        createMarkers,
        addMarkersToMap,
        setMapCenter,
        changeMarkerStatus,
        alertInfoWindow,
        closeInfoWindow
    }
}